package pl.edu.agh.neuraleconomy.dataimporter.xls;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import pl.edu.agh.neuraleconomy.common.utils.FileUtils;

public class XlsDataParser {
	private Logger logger = Logger.getLogger(getClass());

	public List<List<Cell>> processSheet(InputStream stream) {
		NPOIFSFileSystem sys = null;
		File tempFile = null;
		try {
			tempFile = File.createTempFile("sheet", ".xslx");
			FileUtils.saveToFile(stream, tempFile);
			sys = new NPOIFSFileSystem(tempFile);
			//HSSFWorkbook workbook = new HSSFWorkbook(sys.getRoot(), false);
			HSSFWorkbook workbook = (HSSFWorkbook) WorkbookFactory.create(sys);
			HSSFSheet sheet = workbook.getSheetAt(0);

			List<List<Cell>> rows = new LinkedList<List<Cell>>();
			Iterator<Row> rowIterator = sheet.iterator();

			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				List<Cell> rowCells = new LinkedList<Cell>();
				Iterator<Cell> cellIterator = row.cellIterator();

				while (cellIterator.hasNext()) {
					Cell cell = cellIterator.next();
					rowCells.add(cell);
				}
				rows.add(rowCells);
			}
			return rows;
		} catch (Exception e) {
			logger.error("Nie udalo sie sparsowac arkusza", e);
			return null;
		}finally{
			try{
				sys.close();
				tempFile.delete();
			}catch(Exception e){}
		}
	}

	public String getStringValue(Cell cell) {
		if (cell == null) {
			return null;
		}
		return cell.getStringCellValue().trim();
	}

	public BigDecimal getNumericValue(Cell cell) {
		if (cell == null) {
			return null;
		}
		return new BigDecimal(cell.getNumericCellValue()).setScale(2, BigDecimal.ROUND_HALF_EVEN);
	}
}
